package cn.xc.system.service.impl;

import cn.xc.system.domain.Role;
import cn.xc.system.mapper.RoleMapper;
import cn.xc.system.service.IRoleService;
import cn.xc.basic.service.impl.BaseServiceImpl;
import com.sun.mail.imap.protocol.ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    public void initRelationTable(Role role){
        Long roleId = role.getId();

        List<Long> menus = role.getMenus();
        if (menus.size()>0){
            roleMapper.saveRoleMenus(roleId,menus);
        }

        List<Long> permissions = role.getPermissions();
        if (permissions.size() > 0){
            roleMapper.saveRolePermissons(roleId,permissions);
        }


    }

    /**
     * 保存對象權限
     * @param role
     */
    @Override
    @Transactional
    public void add(Role role) {
        super.add(role);
        initRelationTable(role);
    }

    /**
     * 刪除對象權限
     * @param id
     */
    @Transactional
    @Override
    public void del(Long id) {
        roleMapper.removeRermissionByRoleId(id);
        roleMapper.removeMenuByRoleId(id);
        super.del(id);
    }

    /**
     * 編輯對象權限
     * @param role
     */
    @Transactional
    @Override
    public void update(Role role) {
        super.update(role);
        roleMapper.removeRermissionByRoleId(role.getId());
        roleMapper.removeMenuByRoleId(role.getId());
        initRelationTable(role);
    }

    @Override
    public void patchDel(List<Long> ids) {
        for (Long id : ids){
            del(id);
        }
    }
}
